//
//  ReactRootViewManager.m
//  steamRoom
//
//  Created by 安建伟 on 2019/7/19.
//  Copyright © 2019 com.thingcom. All rights reserved.
//

#import "ReactRootViewManager.h"

@implementation ReactRootViewManager

- (void)dealloc {
    _rootViewMap = nil;
    [_bridge invalidate];
}

+ (instancetype)manager {
    static ReactRootViewManager * _rootViewManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _rootViewManager = [[ReactRootViewManager alloc] init];
    });
    return _rootViewManager;
}

- (instancetype)init {
    if (self = [super init]) {
        _rootViewMap = [NSMutableDictionary dictionaryWithCapacity:0];
        _bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:nil];
    }
    return self;
}

- (void)preLoadRootViewWithName:(NSString *)viewName {
    [self preLoadRootViewWithName:viewName initialProperty:nil];
}

- (void)preLoadRootViewWithName:(NSString *)viewName initialProperty:(NSDictionary *)initialProperty {
    if (!viewName && [_rootViewMap objectForKey:viewName]) {
        return;
    }
    // 由bridge创建rootView
    RCTRootView * rnView = [[RCTRootView alloc] initWithBridge:self.bridge
                                                    moduleName:viewName
                                             initialProperties:initialProperty];
    [_rootViewMap setObject:rnView forKey:viewName];
}

- (RCTRootView *)rootViewWithName:(NSString *)viewName {
    if (!viewName) {
        return nil;
    }
    return [self.rootViewMap objectForKey:viewName];
}

#pragma mark - RCTBridgeDelegate
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge {
    return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
}


@end
